<?php

/**
 * usuario actions.
 *
 * @package    sispatr
 * @subpackage usuario
 * @author     Foxsis
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class usuarioActions extends sfActionsFoxsis
{
	public function clearSession()
	{
		if(isset($_SESSION['residentes']))
    		unset($_SESSION['residentes']);
    	if(isset($_SESSION['removerResidentes']))
    		unset($_SESSION['removerResidentes']);
	}

	public function executeIndex(sfWebRequest $request)
	{
		$this->clearSession();

		return $this->forward('usuario', 'list');
	}

	public function executeList()
	{
		$this->clearSession();

		$paginaAtual = $this->_setActualPage();
		$this->filter = $this->_getFilter();
		$listQuery = UsuarioTable::consultarUsuario($this->filter);

		## cria o paginador
		$this->getContext()->getConfiguration()->loadHelpers('Url');
		$this->pager_layout = new Foxsis_Pager_Layout(
			$pager = new Foxsis_Doctrine_Pager(
				$listQuery,
				$paginaAtual,
				25
			),
			new Doctrine_Pager_Range_Sliding(array('chunk' => MAX_PAGER_LINKS)),
			url_for('usuario/list', array('absolute'=>true))
		);

		## executa a consulta
		$this->usuario_list = $this->pager_layout->execute();
		$this->form = new UsuarioForm();

		$this->setTemplate('index');

		if(($this->hasRequestParameter('pg_num')) || $this->getRequestParameter('filtro'))
        	$this->setTemplate('_grid');
	}

	public function executeFilter()
	{
		$filter = new Filtro(
		$this->getRequestParameter(sfActionsFoxsis::FILTER_SESSION_USER_ATTRIBUTE)
		);

		$filter->setCulture($this->getUser()->getCulture());
		$this->getUser()->setAttribute('pg_num',1,$this->getModuleName());

		$this->getUser()->setAttribute(
		sfActionsFoxsis::FILTER_SESSION_USER_ATTRIBUTE,
		serialize($filter),
		$this->getModuleName()
		);

		return $this->forward($this->getModuleName() , 'list');
	}

	public function executeNew(sfWebRequest $request)
	{
		$this->form = new UsuarioForm();

		if(isset($_SESSION['residentes']))
			$this->ar_residentes = $_SESSION['residentes'];
		else
			$this->ar_residentes = array();
			
		$this->residente = array();
	}

	public function executeCreate(sfWebRequest $request)
	{
		$this->forward404Unless($request->isMethod(sfRequest::POST));
		$this->form = new UsuarioForm();
		$this->processForm($request, $this->form);
		$this->forward($this->getModuleName(), 'new');
	}

	public function validateCreate()
	{
		return true;
	}

	public function handleErrorCreate()
	{
		return $this->forward($this->getModuleName(), 'new');
	}

	public function executeEdit(sfWebRequest $request)
	{
		$this->forward404Unless($usuario = Doctrine::getTable('Usuario')->find(array($request->getParameter('id_usuario'))), sprintf('Object usuario does not exist (%s).', $request->getParameter('id_usuario')));
		$this->form = new UsuarioForm($usuario);

		$this->ar_residentes = UsuarioTable::carregarResidentes($this->form->getObject()->getIdUsuario());
		
		$this->residente = null;
		if($this->hasRequestParameter('residente')) {
			$this->residente = array('key' => $this->getRequestParameter('residente'));
		}
	}

	public function executeUpdate(sfWebRequest $request)
	{
		$this->forward404Unless($request->isMethod(sfRequest::POST) || $request->isMethod(sfRequest::PUT));
		$this->forward404Unless($usuario = Doctrine::getTable('Usuario')->find(array($request->getParameter('id_usuario'))), sprintf('Object usuario does not exist (%s).', $request->getParameter('id_usuario')));
		$this->form = new UsuarioForm($usuario);

		$this->processForm($request, $this->form);

		$this->forward($this->getModuleName(), 'edit');
	}

	public function validateUpdate()
	{
		return true;
	}

	public function handleErrorUpdate()
	{
		return $this->forward($this->getModuleName(), 'edit');
	}

	public function executeDelete(sfWebRequest $request)
	{
		try
		{
			$request->checkCSRFProtection();

			$this->forward404Unless($usuario = Doctrine::getTable('Usuario')->find(array($request->getParameter('id_usuario'))), sprintf('Object usuario does not exist (%s).', $request->getParameter('id_usuario')));

			// carrego os residentes
			$residentes = UsuarioTable::carregarResidentes($usuario->getIdUsuario());

			// removo os residentes
			UsuarioTable::removerResidentes($usuario->getIdUsuario());
			$usuario->delete();

			$this->redirect('usuario/index');
		}
		catch(Excepiton $e)
		{
			$this->getUser()->setFlash('erro', $e->getMessage());
			$this->redirect('usuario/index');
		}

	}

	protected function processForm(sfWebRequest $request, sfForm $form)
	{
		try
		{
			$form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
			if ($form->isValid())
			{
				$usuario = $form->save();
				
				if($this->getRequestParameter('gerar_prontuario'))
				{
					$nu_prontuario = UsuarioTable::gerarNumeroProntuario();
					$usuario->set('prontuario', $nu_prontuario);
					
					$usuario->save();
				}

				$this->getUser()->setFlash('mensagem', 'Dados salvos com sucesso.');
				$this->redirect('usuario/edit?id_usuario='.$usuario->getIdUsuario());
			}
			else
			{
				throw new Exception($form->getErrorSchema());
			}
		}
		catch(Exception $e)
		{
			$this->getUser()->setFlash('erro', $e->getMessage());
		}
	}

	public function montarLista($lista = array())
	{

		$ar_retorno = array();
		foreach($lista as $item)
		{
			$ar_retorno[] = array(
				'id_usuario' 		=> $item['id_usuario'],
				'nome'				=> $item['nome'],
				'parentesco' 		=> $item['parentesco'],
				'sexo'  			=> $item['sexo'],
				'data_nascimento'  	=> $item['data_nascimento'],
				'grau_instrucao'  	=> $item['grau_instrucao'],
				'ocupacao'  		=> $item['ocupacao'],
				'renda_mensal'  	=> $item['renda_mensal']
			);
		}

		return $ar_retorno;
	}

	public function executeSalvarResidente()
	{
		$key = $this->getRequestParameter('key');
		$usuario = Doctrine::getTable('Usuario')->find($this->getRequestParameter('id_usuario'));
		
		$formData = new FormData($this->getRequestParameter('residente'));
		$formData->setCulture($this->getUser()->getCulture());	
		
		
		if($key == '')
		{
			$ObjResidente = new Usuario();	
		}
		else
		{
			$ObjResidente = Doctrine::getTable('Usuario')->find($key);
		}
		
		
		$ObjResidente->set('id_usuario_pai', $usuario->getIdUsuario());
		$ObjResidente->set('prontuario', 	 $usuario->getProntuario());
		$ObjResidente->set('nome', 			 $formData->get('nome'));
		$ObjResidente->set('parentesco', 	 $formData->get('parentesco'));
		$ObjResidente->set('sexo', 			 $formData->get('sexo'));
		$ObjResidente->set('data_nascimento',$formData->get('data_nascimento', FormData::DATE));
		$ObjResidente->set('grau_instrucao', $formData->get('grau_instrucao'));
		$ObjResidente->set('ocupacao',	 	 $formData->get('ocupacao'));
		$ObjResidente->set('renda_mensal', 	 $formData->get('renda_mensal', FormData::FLOAT));
		$ObjResidente->save();
		
		$this->setTemplate('_listResidentes');
		$this->ar_residentes = UsuarioTable::carregarResidentes($usuario->getIdUsuario());
	}

	public function executeRemoverResidente()
	{
		try{
			$chave = $this->getRequestParameter('chave');
	
			$residente = Doctrine::getTable('Usuario')->find($chave);
			$residente->delete();
	
			$result = array('success'=>true);
		} 
		catch(Exception $e)
		{
			$result = array('error'=>utf8_encode($e->getMessage()));
		}

		$this->getResponse()->setHttpHeader('Content-type','application/json; charset=utf-8');
		return $this->renderText(json_encode($result));
	}

	public function executeCarregarResidente()
	{
		$chave = $this->getRequestParameter('chave');
		$usuario = Doctrine::getTable('Usuario')->find($chave);
		$this->forward404Unless($usuario, sprintf('Object usuario does not exist (%s).', $chave));
		
		$usuario = $usuario->toArray();
		
		$this->getResponse()->setHttpHeader('Content-type','application/json; charset=utf-8');
		return $this->renderText(json_encode($usuario));
	}

	/*public function executeAutocomplete(sfWebRequest $request)
	{
		$query = strtoupper($request->getParameter('q'));
		$limit = $request->getParameter('limit');

		$result = UsuarioTable::autocomplete($query, $limit);

		$this->getResponse()->setHttpHeader('Content-type','application/json; charset=utf-8');
		return $this->renderText(json_encode($result));
	}*/

	public function executePlanilha(sfWebRequest $request)
	{
		if(isset($_SESSION['erros']) && count($_SESSION['erros']))
			$this->executeFinalizarImportacao();
		else
			unset($_SESSION['erros']);
	}
	
	public function executeImportarPlanilha(sfWebRequest $request)
	{
		set_time_limit(0);
		//$this->setTemplate('planilha');

		$file = $_FILES['arquivo'];
		if(@move_uploaded_file($file['tmp_name'], sfConfig::get('sf_upload_dir').'/planilha.xls')){

			$data = new sfExcelReader(sfConfig::get('sf_upload_dir').'/planilha.xls');

			$totalLinhas = $data->rowcount();
			$totalColunas= $data->colcount();

			for($i = 1; $i <= $totalLinhas; $i++){
				for($j = 1; $j <= $totalColunas; $j++){
					$a[$i][$j] = $data->val($i,$j);
				}
			}

			if(count($a))
			{
				$contador = 0;
				$_SESSION['erros'] = array();
				$cont = 0;
				$test = array_shift($a);
				$total = count($a);
				foreach($a as $key => $item)
				{
					try {
						$formData = new FormData($item, true);
						$formData->setCulture($this->getUser()->getCulture());
						
						// verifico se já tem um usuario com o prontuario informado
						//$usuario = UsuarioTable::carregarUsuario(array('prontuario = '. strtoupper(trim($formData->get('1')))));
						
						//if(!count($usuario)){
							$usuario = new Usuario();
							$usuario->set('prontuario', 		strtoupper($formData->get('1')));
							$usuario->set('nome', 				($formData->get('2') != '')? strtoupper($formData->get('2')) : '--');
							$usuario->set('data_nascimento', 	$formData->get('3', FormData::DATE));
							$usuario->set('endereco', 			strtoupper($formData->get('4')));
							$usuario->set('regiao', 			strtoupper($formData->get('5')));
							$usuario->set('situacao',			Util::verificarSituacao($formData->get('6')));
							$usuario->set('uf',					$formData->get('7'));						
							$usuario->set('observacao', 		strtoupper($formData->get('8') . $formData->get('9')));
							$usuario->save();
							$usuario->free(true);
							unset($usuario);
							
							$contador++;
						//}
					} catch(Exception $e) {
						$contador = $contador - 1;
						
						$_SESSION['erros'][$cont]['prontuario'] = $formData->get('1');
						$_SESSION['erros'][$cont]['erro'] = $e->getMessage();
						continue;
					}
					$con++;
				}
				unlink(sfConfig::get('sf_upload_dir').'/planilha.xls');
				
				if($contador == $total)
					$this->getUser()->setFlash('mensagem', 'Dados importados com sucesso. Total de ' . $contador . ' de ' . $total, true);
				elseif($contador != 0 && $contador != $total) 
					$this->getUser()->setFlash('alert', 'Dados importados com sucesso. <br /> Total de ' . $contador . ' de ' . $total, true);
				else 
					$this->getUser()->setFlash('alert', 'Nenhum registro foi importado. <br /> Verifique se os dados estão duplicados.', true);
			}
		} else {
			$this->getUser()->setFlash('erro', 'Erro ao importar planilha. Por favor tente novamente.', true);
		}
		
		return $this->redirect('@planilha');
	}
	
	public function executeFinalizarImportacao()
	{
		if(count($_SESSION['erros'] > 0))
		{
			ini_set("display_errors", "off");
		    $this->usuarios = $_SESSION['erros'];
		
		    $html = "<table border='1'>";
		    $html.= "<tr>\n<th>Prontuario</th>\n";
		    $html.= "<th>Erro</th></tr>";
		    
		    foreach($this->usuarios as $usuario)
		    {
		    	$html.= "<tr>\n";	
		    	$html.= "<td>{$usuario['prontuario']}</td>\n";
		    	$html.= "<td>{$usuario['erro']}</td>\n";
		    	$html.= "</tr>\n";	
		    }
		    
		    $html.= "</table>";
		    unset($_SESSION['erros']);
		    Util::htmltoXLS($html, 'pronturaios_nao_importados.xls');
		    
		} else {
			$this->redirect('@planilha');
		}
	}
	
	public function executeImprimir(sfWebRequest $request)
	{
		ini_set("display_errors", "off");
	    $this->usuario = Doctrine::getTable('Usuario')->find($request->getParameter('id_usuario'));
	
	    //code to generate pdf
	    $html = utf8_decode(Util::getHtmlContent($this));
	    $mpdf = new CrasMPDF('prontuario_'.$this->usuario['prontuario'], $html);
	    exit();
	}
	
	public function executeExportar(sfWebRequest $request)
	{
		$params = array(
			"id_usuario_pai IS NULL"
		);
		
		$this->usuarios = UsuarioTable::carregarUsuario($params);
		
		$html = Util::getHtmlContent($this);
		Util::htmltoXLS(utf8_decode($html), 'planilha.xls');
		exit();
	}
}